<?php defined('SYSPATH') OR die('No direct access allowed.');
	class Auth_Controller extends Controller {
		public function __construct() {
			parent::__construct();

			$this->model = new Auth_Model();
		}

		public function login() {
			$username = $_POST['username'];
			$password = $_POST['password'];
			$timeout = $_POST['timeout'];

			// FIXME raise all hell if any of them are missing or invalid.

			list($userid, $pass) = $this->model->getIdPassword($username);

			if ($pass == sha1($username . $password)) {
				$token = sha1( $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] );

				$this->model->setSession($token, $userid, gmtime(), $timeout);

				cookie::set(
					'fhus',
					$token,
					30000000, // 3 million seconds ~ 1 year
					'/',
					$_SERVER['SERVER_NAME'] // use $config['cookie_domain'] eventually
				);
			} else {
				// Don't accept the login
			}
		}

		public function logout() {
			$token = cookie::get('fhus');

			$this->model->deleteSession($token);
			cookie::delete('fhus');
		}

		public function isLoggedIn() {
			$token = cookie::get('fhus');
			
			if ($token == null) {
				return false;
			}
			
			list($userid, $lastactive, $timeout) = $this->model->getSession($token);
			
			if ($userid == null) {
				cookie::delete('fhus');
				return false;
			} else {
				if (gmtime() > $lastactive - $timeout) {
					cookie::delete('fhus');
					return false;
				} else {
					return true;
				}
			}
		}
	}
